import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author 35326
 * 2021/3/23 7:46
 * 线程按序打印
 */
public class ThreadPrint {
}

class AlternateDemo{
	//表示当前正在执行线程的标记
	private int number=1;

	private Lock lock = new ReentrantLock();
	private Condition conditionA=lock.newCondition();
	private Condition conditionB=lock.newCondition();
	private Condition conditionC=lock.newCondition();
	public void loopA(int totalLoop){
		lock.lock();
		try{
			//1、判断
			if(this.number!=1){
				conditionA.await();
			}
			//2、打印
			for (int i = 0; i < 5; i++) {
				System.out.println(Thread.currentThread().getName() + "-" + i + "这是第" + totalLoop + "轮");
			}
			//2、唤醒
			number=2;
			conditionB.signal();
		}catch (InterruptedException e){

		}finally {
			lock.unlock();
		}
	}
	public void loopB(int totalLoop){
		lock.lock();
		try{
			//1、判断
			if(this.number!=2){
				conditionB.await();
			}
			//2、打印
			for (int i = 0; i < 15; i++) {
				System.out.println(Thread.currentThread().getName() + "-" + i + "这是第" + totalLoop + "轮");
			}
			//2、唤醒
			number=3;
			conditionC.signal();
		}catch (InterruptedException e){

		}finally {
			lock.unlock();
		}
	}

	public void loopC(int totalLoop){
		lock.lock();
		try{
			//1、判断
			if(this.number!=3){
				conditionC.await();
			}
			//2、打印
			for (int i = 0; i < 20; i++) {
				System.out.println(Thread.currentThread().getName() + "-" + i + "这是第" + totalLoop + "轮");
			}
			//2、唤醒
			number=1;
			conditionA.signal();
		}catch (InterruptedException e){

		}finally {
			lock.unlock();
		}
	}

	public static void main(String[] args) {
		AlternateDemo alternateDemo = new AlternateDemo();
		new Thread(()->{
			for (int i = 0; i < 20; i++) {
				alternateDemo.loopA(i);
			}
		},"A").start();
		new Thread(()->{
			for (int i = 0; i < 20; i++) {
				alternateDemo.loopB(i);
			}
		},"B").start();
		new Thread(()->{
			for (int i = 0; i < 20; i++) {
				alternateDemo.loopC(i);
			}
		},"C").start();
	}
}
